<script setup lang="tsx">
import { useRouter } from 'vue-router'
import { ref, unref } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useI18n } from '@/hooks/web/useI18n'
import useSchema from './components/hooks/useSchema'
import { ActionButtonsTemplate } from '@/api/global/types'
import { CurdData } from '@/api/payment/types'
import { getListApi, delListApi, getPaymentStatusApi, examineDataApi } from '@/api/payment'
import { ElMessage } from 'element-plus'
import { AllSchemas, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

defineOptions({
  name: 'PaymentManagement'
})

const { push } = useRouter()
const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  currentPageSize: 10,
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState

    const res = await getListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()

// Begin CRUD Template Block
// ------------------------
const delData = async (row: CurdData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: CurdData) => v.id) || []
  if (ids.value.length === 0) {
    ElMessage.error(t('common.selectData'))
    return
  }
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: CurdData, type: string) => {
  push(`/purchase/payment-order-management/${type}?id=${row.id}`)
}
const actionButtonsTemplate: ActionButtonsTemplate = {
  length: 5,
  template: (data: any) => {
    return (
      <>
        {data.row.status == 10 && (
          <BaseButton size="small" onClick={() => action(data.row, 'edit')}>
            {t('action.edit')}
          </BaseButton>
        )}
        {data.row.status == 20 && (
          <BaseButton size="small" type="success" onClick={() => action(data.row, 'proof')}>
            {t('payment.upload')}
          </BaseButton>
        )}
        <BaseButton size="small" type="success" onClick={() => action(data.row, 'detail')}>
          {t('action.detail')}
        </BaseButton>
        {data.row.status == 1 && (
          <BaseButton size="small" type="primary" onClick={() => examineHandle(data.row, 1)}>
            {t('purchase.examine_pass')}
          </BaseButton>
        )}
        {data.row.status == 1 && (
          <BaseButton size="small" type="primary" onClick={() => examineHandle(data.row, 2)}>
            {t('common.reject')}
          </BaseButton>
        )}
        {[1, 4].includes(data.row.status) && userStore.getUserInfo?.id == data.row.creator && (
          <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
            {t('common.cancelExamine')}
          </BaseButton>
        )}
      </>
    )
  }
}
const allSchemas = ref<AllSchemas>({
  searchSchema: [], // 确保与接口匹配
  tableColumns: [] // 确保与接口匹配
})
const getSelectData = async () => {
  const resp = await getPaymentStatusApi({ field: 'all' })
  const { crudSchemas } = useSchema(
    actionButtonsTemplate,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    resp.data
  )
  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)
  // 合并新的数据，确保不改变原有数据的类型
  allSchemas.value = {
    searchSchema: newSchemas.searchSchema || [],
    tableColumns: newSchemas.tableColumns || []
  }
}
getSelectData()
// End CRUD Template Block
// ------------------------

const AddAction = () => {
  push('/purchase/payment-order-management/add')
}
const examineHandle = (row, type) => {
  ElMessageBox.confirm(t('common.message.operate'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let params = {
        status: type,
        id: row.id
      }
      const resp = await examineDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('common.success'))
        getList()
      }
    })
    .catch(() => {})
}
const delLoading = ref(false)
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('action.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('common.cancelExamine') }}
      </BaseButton>
    </div>

    <Table
      showAction
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
